
const express=require('express');
const router=express.Router();
const mongoose =require("mongoose");

const InWareHouseBill=require("../../models/InWareHouseBill");
const BilletWarehouse=require("../../models/BilletWarehouse");
const BilletedWarehouse=require("../../models/BilletedWarehouse");
const Variety=require("../../models/Variety");
const SaleBill = require('../../models/SaleBill');
const Csutomer = require('../../models/Customer');
const ReturnedBill = require('../../models/ReturnedBill');
const PaymentRecord = require('../../models/PaymentRecord.js');
const ProcessBill = require("../../models/processBill.js");
const ProcessingCompany = require('../../models/ProcessingCompany');
const ProcessReturnBill = require('../../models/processReturnBill');


//===========================入库操作=======================================//

router.post("/inWareHouseBill/add",(req,res)=>{
    let inWareHouseBill=new InWareHouseBill({
        name:req.query.name,
        number:req.query.number,
        piece:req.query.piece,
        length:req.query.length,
        warehouse:req.query.warehouse,
        date:req.query.date,
        operator:req.query.operator,
        remark:req.query.remark,
    })
    inWareHouseBill.save()
    .then(bill=>res.json({
        code:200,
        data:bill
    }))
    .catch(err=>{
        res.json({
            code:404,
            data:err
        })
        console.log(err)
    })
})

router.post("/inWareHouseBill/getList",(req,res)=>{
    const limit=Number(req.query.limit);
    const page=Number(req.query.page);
    const match = {};
    const datelimit = {};
    let dateflag = false;
    for(let i in req.query){
        if(i!='limit' && i!=='page' && i!='datestart' && i!='dateend' && i!="sort"){
            match[i] = req.query[i];
        }
        else if(i =='datestart'){
            datelimit.$gte = req.query[i];
            dateflag = true;
        }
        else if(i == 'dateend'){
            datelimit.$lte = req.query[i];
            dateflag = true;
        }
    }
    const sortLimit = {date:req.query.sort?Number(req.query.sort):-1}
    if(dateflag) match['date'] = datelimit;
    InWareHouseBill.find(match)
    .sort(sortLimit)
    .then(bills=>{
        const pageList = bills.filter((item, index) => index < limit * page && index >= limit * (page - 1))
        res.json({
            code:200,
            list:pageList,
            total:bills.length
        });
    })
})

router.post("/inWareHouseBill/fetchSelectItem",(req,res)=>{
    const data = {
        code:200,
        warehouse:[],
        goods:[],
        goodsNumber:{},
    }
    BilletWarehouse.find({})
    .then(billetWarehouse=>{
        data.warehouse = billetWarehouse.map(v=>v.name);
        // BilletedWarehouse.find({})
        // .then(billetedWarehouse=>{
            
            // let billetedWarehouseName = billetedWarehouse.map(v=>v.name);
            // data.warehouse = data.warehouse.concat(billetedWarehouseName);
            Variety.find({})
            .then(goods=>{
                for(let i=0;i<goods.length;i++){
                    data.goods.push(goods[i].name);
                    data.goodsNumber[goods[i].name] = goods[i].number.map(v=>v.code);
                }
                res.json(data);
            })
            .catch(err=>{
                res.json(data)
                console.log(err)
            })
        // })
        
        
    })
    .catch(err=>{
        res.json(data)
        console.log(err)
    })
    
})

router.post("/inWareHouseBill/update",(req,res)=>{
    const id = req.body._id;
    const data = {
        name:req.body.name,
        number:req.body.number,
        piece:req.body.piece,
        length:req.body.length,
        warehouse:req.body.warehouse,
        date:req.body.date,
        operator:req.body.operator,
        remark:req.body.remark,
    }
    InWareHouseBill.updateOne({_id: id}, data)
    .then(data=>{
        // console.log('update',data);
        res.json({
            code:200,
            data:data
        });
    })
})

router.post("/inWareHouseBill/delete",(req,res)=>{
    const id = req.query._id;
    InWareHouseBill.deleteOne({_id: id})
    .then(()=>{
        // console.log('delete',data);
        res.json({
            code:200,
            message:'删除成功'
        });
    })
})

//==============================================销售单==============================================

router.post("/saleBill/add",(req,res)=>{
    let outPiece = req.query.outPiece;
    let outLength = req.query.outLength;
    let name = req.query.name, number = req.query.number,warehouse = req.query.warehouse;
    ProcessReturnBill.find({name:name, number:number, warehouse: warehouse})
    .then((bills)=>{
        SaleBill.find({name, number, warehouse})
            .then(( pbills)=>{
                ReturnedBill.find({name, number, warehouse})
                .then((rbills)=>{
                    var leftPiece = 0;
                    var leftLength = 0;
                    for(let i=0;i<bills.length;i++){
                        leftPiece += bills[i].piece;
                        leftLength += bills[i].length;
                    }
                    for(let i=0;i<pbills.length;i++){
                        leftPiece -= pbills[i].outPiece;
                        leftLength -= pbills[i].outLength;
                    }
                    for(let i=0;i<rbills.length;i++){
                        leftPiece += rbills[i].inPiece;
                        leftLength += rbills[i].inLength;
                    }
                    leftLength=Number(leftLength.toFixed(1));
                    if(leftPiece < outPiece || leftLength < outLength){
                        res.json({
                            code:200,
                            leftPiece: leftPiece,
                            leftLength: leftLength
                        });
                    }
                    else{
                        let saleBill=new SaleBill({
                            saleCode:Date.now().toString(),
                            name:req.query.name,
                            number:req.query.number,
                            customer:req.query.customer,
                            outPiece:req.query.outPiece,
                            outLength:req.query.outLength,
                            price:req.query.price,
                            money:req.query.money,
                            warehouse:req.query.warehouse,
                            date:req.query.date,
                            operator:req.query.operator,
                            remark:req.query.remark,
                        })
                        saleBill.save()
                        .then(bill=>res.json({
                            code:200,
                            data:bill
                        }))
                        .catch(err=>{
                            res.json({
                                code:404,
                                data:err
                            })
                            console.log(err)
                        })
                    }
                    
            })
                
        })
     })
    
})

router.post("/saleBill/getList",(req,res)=>{
    const limit=Number(req.query.limit);
    const page=Number(req.query.page);
    const match = {};
    const datelimit = {};
    let dateflag = false;
    for(let i in req.query){
        if(i!='limit' && i!=='page' && i!='datestart' && i!='dateend' && i!="sort"){
            match[i] = req.query[i];
        }
        else if(i =='datestart'){
            datelimit.$gte = new Date(req.query[i]);
            dateflag = true;
        }
        else if(i == 'dateend'){
            datelimit.$lte = new Date(req.query[i]);
            dateflag = true;
        }
    }
    const sortLimit = {date:req.query.sort?Number(req.query.sort):-1}
    if(dateflag) match['date'] = datelimit;
    // SaleBill.find(match)
    // .sort(sortLimit)
    // .then(bills=>{
    //     const pageList = bills.filter((item, index) => index < limit * page && index >= limit * (page - 1))
    //     res.json({
    //         code:200,
    //         list:pageList,
    //         total:bills.length
    //     });
    // })
    SaleBill.aggregate([{$match:match},
        {
            $lookup:{
                from:'paymentrecords',
                localField:'saleCode',
                foreignField:'saleCode',
                as:'paymentRecords',
            },
            
        },
        {
            $lookup:{
                from:'returnedbills',
                localField:'saleCode',
                foreignField:'saleCode',
                as:'returnedBills',
            }
        },
    {$sort:sortLimit},
    {$skip: limit * (page - 1)},
    {$limit: limit},
    ])
    .exec((error, bills)=>{
        // console.log(bills)
        // const pageList = bills.filter((item, index) => index < limit * page && index >= limit * (page - 1))
      SaleBill.find(match).countDocuments().then(count=>{
        res.json({
            code:200,
            list:bills,
            total:count
        });
      })
    })
})

router.post("/saleBill/fetchSelectItem",(req,res)=>{
    const data = {
        code:200,
        warehouse:[],
        goods:[],
        goodsNumber:{},
        customers:[],
    }
    BilletedWarehouse.find({})
    .then(billetedWarehouse=>{
        data.warehouse = billetedWarehouse.map(v=>v.name);
        Variety.find({})
        .then(goods=>{
            for(let i=0;i<goods.length;i++){
                data.goods.push(goods[i].name);
                data.goodsNumber[goods[i].name] = goods[i].number
            }
            Csutomer.find({})
            .then(customers=>{
                data.customers = customers.map(v=>v.name);
                res.json(data);
            })
            .catch(err=>{
                res.json(data)
                console.log(err)
            })
        })
        .catch(err=>{
            res.json(data)
            console.log(err)
        })
    })
    .catch(err=>{
        res.json(data)
        console.log(err)
    })
    
})

router.post("/saleBill/update",(req,res)=>{
    const id = req.body._id;
    let outPiece = req.body.outPiece;
    let outLength = req.body.outLength;
    let name = req.body.name, number = req.body.number,warehouse = req.body.warehouse;
    ProcessReturnBill.find({name:name, number:number, warehouse: warehouse})
    .then((bills)=>{
        SaleBill.find({name, number, warehouse})
            .then(( pbills)=>{
                ReturnedBill.find({name, number, warehouse})
                .then((rbills)=>{
                    var leftPiece = 0;
                    var leftLength = 0;
                    for(let i=0;i<bills.length;i++){
                        leftPiece += bills[i].piece;
                        leftLength += bills[i].length;
                    }
                    for(let i=0;i<pbills.length;i++){
                        if(pbills[i]._id!=id){
                            leftPiece -= pbills[i].outPiece;
                            leftLength -= pbills[i].outLength;
                        }
                    }
                    for(let i=0;i<rbills.length;i++){
                        leftPiece += rbills[i].inPiece;
                        leftLength += rbills[i].inLength;
                    }
                    if(leftPiece < outPiece || leftLength < outLength){
                        res.json({
                            code:200,
                            leftPiece: leftPiece,
                            leftLength: leftLength
                        });
                    }
                    else{
                        const data = {
                            name:req.body.name,
                            number:req.body.number,
                            customer:req.body.customer,
                            outPiece:req.body.outPiece,
                            outLength:req.body.outLength,
                            price:req.body.price,
                            money:req.body.money,
                            warehouse:req.body.warehouse,
                            date:req.body.date,
                            operator:req.body.operator,
                            remark:req.body.remark,
                        }
                        SaleBill.updateOne({_id: id}, data)
                        .then(()=>{
                            // console.log('update',data);
                            res.json({
                                code:200,
                                data:data,
                            });
                        })
                    }
                })
            })
        })
    
})

router.post("/saleBill/delete",(req,res)=>{
    const id = req.query._id;
    SaleBill.deleteOne({_id: id})
    .then(()=>{
        // console.log('delete',data);
        res.json({
            code:200,
            message:'删除成功'
        });
    })
})

// =========================================退货===========================================
router.post("/returnedBill/add",(req,res)=>{
    
    let returnBill=new ReturnedBill({
        returnedCode:Date.now().toString(),
        saleCode:req.query.saleCode,
        saleId:mongoose.Types.ObjectId(req.query._id),
        name:req.query.name,
        number:req.query.number,
        customer:req.query.customer,
        inPiece:req.query.inPiece,
        inLength:req.query.inLength,
        price:req.query.price,
        money: req.query.price * req.query.inLength,
        warehouse:req.query.warehouse,
        date:req.query.date,
        operator:req.query.operator,
        remark:req.query.remark,
    })
    returnBill.save()
    .then(bill=>res.json({
        code:200,
        data:bill
    }))
    .catch(err=>{
        res.json({
            code:404,
            data:err
        })
        console.log(err)
    })
})


router.post("/returnedBill/getList",(req,res)=>{
    const limit=Number(req.query.limit);
    const page=Number(req.query.page);
    const match = {};
    const datelimit = {};
    let dateflag = false;
    for(let i in req.query){
        if(i!='limit' && i!=='page' && i!='datestart' && i!='dateend' && i!="sort"){
            match[i] = req.query[i];
        }
        else if(i =='datestart'){
            datelimit.$gte = new Date(req.query[i]);
            dateflag = true;
        }
        else if(i == 'dateend'){
            datelimit.$lte = new Date(req.query[i]);
            dateflag = true;
        }
    }
    const sortLimit = {date:req.query.sort?Number(req.query.sort):-1}
    if(dateflag) match['date'] = datelimit;
    ReturnedBill.find(match)
    .sort(sortLimit)
    .then(bills=>{
        const pageList = bills.filter((item, index) => index < limit * page && index >= limit * (page - 1))
        res.json({
            code:200,
            list:pageList,
            total:bills.length
        });
    })
})

router.post("/returnedBill/fetchSelectItem",(req,res)=>{
    const data = {
        code:200,
        warehouse:[],
        goods:[],
        goodsNumber:{},
        customers:[],
    }
    BilletedWarehouse.find({})
    .then(billetedWarehouse=>{
        data.warehouse = billetedWarehouse.map(v=>v.name);
        Variety.find({})
        .then(goods=>{
            for(let i=0;i<goods.length;i++){
                data.goods.push(goods[i].name);
                data.goodsNumber[goods[i].name] = goods[i].number
            }
            Csutomer.find({})
            .then(customers=>{
                data.customers = customers.map(v=>v.name);
                res.json(data);
            })
            .catch(err=>{
                res.json(data)
                console.log(err)
            })
        })
        .catch(err=>{
            res.json(data)
            console.log(err)
        })
    })
    .catch(err=>{
        res.json(data)
        console.log(err)
    })
    
})

router.post("/returnedBill/delete",(req,res)=>{
    const id = req.query._id;
    ReturnedBill.deleteOne({_id: id})
    .then(()=>{
        // console.log('delete',data);
        res.json({
            code:200,
            message:'删除成功'
        });
    })
})

router.post("/returnedBill/update",(req,res)=>{
    const id = req.body._id;
    const data = {
        inPiece:req.body.inPiece,
        inLength:req.body.inLength,
        money: req.body.price * req.body.inLength,
        warehouse:req.body.warehouse,
        date:req.body.date,
        operator:req.body.operator,
        remark:req.body.remark,
    }
    ReturnedBill.updateOne({_id: id}, data)
    .then(data=>{
        // console.log('update',data);
        res.json({
            code:200,
            data:data
        });
    })
})

// =========================================付款===========================================
router.post("/paymentRecord/add",(req,res)=>{
    let paymentRecord=new PaymentRecord({
        payCode:Date.now().toString(),
        saleCode:req.query.saleCode,
        saleId:mongoose.Types.ObjectId(req.query._id),
        name:req.query.name,
        number:req.query.number,
        customer:req.query.customer,
        finishPiece:req.query.finishPiece,
        finishLength:req.query.finishLength,
        finishMoney:req.query.finishMoney,
        price:req.query.price,
        date:req.query.date,
        operator:req.query.operator,
        remark:req.query.remark,
    })
    paymentRecord.save()
    .then(bill=>res.json({
        code:200,
        data:bill
    }))
    .catch(err=>{
        res.json({
            code:404,
            data:err
        })
        console.log(err)
    })
})


router.post("/paymentRecord/getList",(req,res)=>{
    const limit=Number(req.query.limit);
    const page=Number(req.query.page);
    const match = {};
    const datelimit = {};
    let dateflag = false;
    for(let i in req.query){
        if(i!='limit' && i!=='page' && i!='datestart' && i!='dateend' && i!="sort"){
            match[i] = req.query[i];
        }
        else if(i =='datestart'){
            datelimit.$gte = new Date(req.query[i]);
            dateflag = true;
        }
        else if(i == 'dateend'){
            datelimit.$lte = new Date(req.query[i]);
            dateflag = true;
        }
    }
    const sortLimit = {date:req.query.sort?Number(req.query.sort):-1}
    if(dateflag) match['date'] = datelimit;
    PaymentRecord.find(match)
    .sort(sortLimit)
    .then(bills=>{
        const pageList = bills.filter((item, index) => index < limit * page && index >= limit * (page - 1))
        res.json({
            code:200,
            list:pageList,
            total:bills.length
        });
    })
})

router.post("/paymentRecord/fetchSelectItem",(req,res)=>{
    const data = {
        code:200,
        warehouse:[],
        goods:[],
        goodsNumber:{},
        customers:[],
    }

    Variety.find({})
    .then(goods=>{
        for(let i=0;i<goods.length;i++){
            data.goods.push(goods[i].name);
            data.goodsNumber[goods[i].name] = goods[i].number
        }
        Csutomer.find({})
        .then(customers=>{
            data.customers = customers.map(v=>v.name);
            res.json(data);
        })
        .catch(err=>{
            res.json(data)
            console.log(err)
        })
    })
    .catch(err=>{
        res.json(data)
        console.log(err)
    })

})

router.post("/paymentRecord/delete",(req,res)=>{
    const id = req.query._id;
    PaymentRecord.deleteOne({_id: id})
    .then(()=>{
        // console.log('delete',data);
        res.json({
            code:200,
            message:'删除成功'
        });
    })
})

router.post("/paymentRecord/update",(req,res)=>{
    const id = req.body._id;
    console.log(req.body)
    const data = {
        finishPiece:req.body.finishPiece,
        finishLength:req.body.finishLength,
        finishMoney:req.body.finishMoney,
        date:req.body.date,
        operator:req.body.operator,
        remark:req.body.remark,
    }
    PaymentRecord.updateOne({_id: id}, data)
    .then(data=>{
        // console.log('update',data);
        res.json({
            code:200,
            data:data
        });
    })
})

// ==================================================销售统计=========================================
router.post("/saleStatistics/fetchSelectItem",(req,res)=>{
    const data = {
        code:200,
        warehouse:[],
        goods:[],
        goodsNumber:{},
        customers:[],
    }
    
    Variety.find({})
    .then(goods=>{
        for(let i=0;i<goods.length;i++){
            data.goods.push(goods[i].name);
            data.goodsNumber[goods[i].name] = goods[i].number
        }
        Csutomer.find({})
        .then(customers=>{
            data.customers = customers.map(v=>v.name);
            res.json(data);
        })
        .catch(err=>{
            res.json(data)
            console.log(err)
        })
    })
    .catch(err=>{
        res.json(data)
        console.log(err)
    })
})

router.post("/saleStatistics/getList",(req,res)=>{
    let query = JSON.parse(req.query.query);
    const limit=Number(query.limit);
    const page=Number(query.page);
    const match = {};
    const datelimit = {};
    let dateflag = false;
    for(let i in query){
        if(i!='limit' && i!=='page' && i!='datestart' && i!='dateend' && i!="sort"){
            match[i] = query[i];
        }
        else if(i =='datestart'){
            datelimit.$gte = new Date(query[i]);
            dateflag = true;
        }
        else if(i == 'dateend'){
            datelimit.$lte = new Date(query[i]);
            dateflag = true;
        }
    }
    const sortLimit = {date:query.sort?Number(query.sort):-1}
    if(dateflag) match['date'] = datelimit;
    let groupWord = {};
    req.query.method = JSON.parse(req.query.method);
    for(let i in req.query.method.checkList){
        if(req.query.method.checkList[i] == "按照客户统计"){
            groupWord.customer = "$customer";
        }
        else if (req.query.method.checkList[i] == "按照产品名称统计"){
            groupWord.name = "$name";
        }
        else if (req.query.method.checkList[i] == "按照产品号码统计"){
            groupWord.number = "$number";
        }
    }
    SaleBill.aggregate([{$match:match},
        {
            $group:{_id:groupWord, 
            outPiece:{$sum:'$outPiece'},
            outLength:{$sum:'$outLength'},
            money:{$sum:'$money'},
            },
        }])
    .exec((error, bills)=>{
        const pageList = bills.filter((item, index) => index < limit * page && index >= limit * (page - 1));
        ReturnedBill.aggregate([{$match:match},
            {
                $group:{_id:groupWord, 
                inPiece:{$sum:'$inPiece'},
                inLength:{$sum:'$inLength'},
                money:{$sum:'$money'},
                },
            }])
            .exec((error, rbills)=>{
                PaymentRecord.aggregate([{$match:match},
                    {
                        $group:{_id:groupWord, 
                        finishPiece:{$sum:'$finishPiece'},
                        finishLength:{$sum:'$finishLength'},
                        money:{$sum:'$finishMoney'},
                        },
                    }])
                    .exec((error, pbills)=>{
                        let obj_1 = {};
                        let obj_2 = {};
                        let obj_3 = {};
                        for(let i in pageList){
                            let key = JSON.stringify(pageList[i]._id);
                            obj_1[key] = pageList[i];
                        }
                        for(let i in rbills){
                            let key = JSON.stringify(rbills[i]._id);
                            obj_2[key] = rbills[i];
                        }
                        for(let i in pbills){
                            let key = JSON.stringify(pbills[i]._id);
                            obj_3[key] = pbills[i];
                        }

                        
                        for(let i in obj_1){
                            obj_1[i].balance = obj_1[i].money;
                            obj_1[i].leftPiece = obj_1[i].outPiece;
                            obj_1[i].leftLength = obj_1[i].outLength;
                            if(obj_2[i] != undefined){
                                obj_1[i].money -= obj_2[i].money;
                                obj_1[i].inPiece = obj_2[i].inPiece;
                                obj_1[i].inLength = obj_2[i].inLength;
                                obj_1[i].leftPiece -= obj_2[i].inPiece;
                                obj_1[i].leftLength -= obj_2[i].inLength;
                            }
                        }

                        for(let i in obj_1){
                            if(obj_3[i] != undefined){
                                obj_1[i].balance -=  obj_3[i].money;
                                obj_1[i].finishPiece = obj_3[i].finishPiece;
                                obj_1[i].finishLength = obj_3[i].finishLength;
                                obj_1[i].leftPiece -= obj_3[i].finishPiece;
                                obj_1[i].leftLength -= obj_3[i].finishLength;
                            }
                        }
                        let pageList_ = [];
                        for(let i in obj_1){
                            pageList_.push(obj_1[i]);
                        }
                        res.json({
                            code:200,
                            list:pageList_,
                            total:bills.length
                        });
                    })
            })
    })
})


// ================================================加工单==================================
router.post("/processBill/add",(req,res)=>{
    let outPiece = req.query.outPiece;
    let outLength = req.query.outLength;
    let name = req.query.name, number = req.query.number,warehouse = req.query.warehouse;
    InWareHouseBill.find({name:name, number:number, warehouse: warehouse})
    .then((bills)=>{
        ProcessBill.find({name, number, warehouse})
            .then(( pbills)=>{
                
                    var leftPiece = 0;
                    var leftLength = 0;
                    for(let i=0;i<bills.length;i++){
                        leftPiece += bills[i].piece;
                        leftLength += bills[i].length;
                    }
                    for(let i=0;i<pbills.length;i++){
                        leftPiece -= pbills[i].outPiece;
                        leftLength -= pbills[i].outLength;
                    }
                    leftLength=Number(leftLength.toFixed(1));
                    if(leftPiece < outPiece || leftLength < outLength){
                        res.json({
                            code:200,
                            leftPiece: leftPiece,
                            leftLength: leftLength
                        });
                    }
                    else{
                        let processBill=new ProcessBill({
                            processCode:Date.now().toString(),
                            name:req.query.name,
                            number:req.query.number,
                            company:req.query.company,
                            outPiece:req.query.outPiece,
                            outLength:req.query.outLength,
                            // inPiece:req.query.inPiece,
                            // inLength:req.query.inLength,
                            // balance:req.query.balance,
                            warehouse:req.query.warehouse,
                            date:req.query.date,
                            operator:req.query.operator,
                            remark:req.query.remark,
                        })
                        processBill.save()
                        .then(bill=>res.json({
                            code:200,
                            data:bill
                        }))
                        .catch(err=>{
                            res.json({
                                code:404,
                                data:err
                            })
                            console.log(err)
                        })
                    }
                })
            })
    
})

router.post("/processBill/getList",(req,res)=>{
    const limit=Number(req.query.limit);
    const page=Number(req.query.page);
    const match = {};
    const datelimit = {};
    let dateflag = false;
    for(let i in req.query){
        if(i!='limit' && i!=='page' && i!='datestart' && i!='dateend' && i!="sort"){
            match[i] = req.query[i];
        }
        else if(i =='datestart'){
            datelimit.$gte = new Date(req.query[i]);
            dateflag = true;
        }
        else if(i == 'dateend'){
            datelimit.$lte = new Date(req.query[i]);
            dateflag = true;
        }
    }
    const sortLimit = {date:req.query.sort?Number(req.query.sort):-1}
    if(dateflag) match['date'] = datelimit;
    ProcessBill.find(match)
    .sort(sortLimit)
    .then(bills=>{
        const pageList = bills.filter((item, index) => index < limit * page && index >= limit * (page - 1))
        res.json({
            code:200,
            list:pageList,
            total:bills.length
        });
    })
})

router.post("/processBill/fetchSelectItem",(req,res)=>{
    const data = {
        code:200,
        warehouse:[],
        goods:[],
        goodsNumber:{},
        companies:[],
    }
    BilletWarehouse.find({})
    .then(billetWarehouse=>{
        data.warehouse = billetWarehouse.map(v=>v.name);
        Variety.find({})
        .then(goods=>{
            for(let i=0;i<goods.length;i++){
                data.goods.push(goods[i].name);
                data.goodsNumber[goods[i].name] = goods[i].number
            }
            ProcessingCompany.find({})
            .then(companies=>{
                data.companies = companies.map(v=>v.name);
                res.json(data);
            })
            .catch(err=>{
                res.json(data)
                console.log(err)
            })
        })
        .catch(err=>{
            res.json(data)
            console.log(err)
        })
    })
    .catch(err=>{
        res.json(data)
        console.log(err)
    })
    
})

router.post("/processBill/update",(req,res)=>{
    const id = req.body._id;
    const data = {
        name:req.body.name,
        number:req.body.number,
        company:req.body.company,
        outPiece:req.body.outPiece,
        outLength:req.body.outLength,
        // inPiece:req.body.inPiece,
        // inLength:req.body.inLength,
        // balance:req.body.balance,
        warehouse:req.body.warehouse,
        date:req.body.date,
        operator:req.body.operator,
        remark:req.body.remark,
    }
    
    let outPiece = req.body.outPiece;
    let outLength = req.body.outLength;
    let name = req.body.name, number = req.body.number,warehouse = req.body.warehouse;
    InWareHouseBill.find({name:name, number:number, warehouse: warehouse})
    .then((bills)=>{
        ProcessBill.find({name, number, warehouse})
            .then(( pbills)=>{
                
                    var leftPiece = 0;
                    var leftLength = 0;
                    for(let i=0;i<bills.length;i++){
                        leftPiece += bills[i].piece;
                        leftLength += bills[i].length;
                    }
                    for(let i=0;i<pbills.length;i++){
                        if(pbills[i]._id!=id){
                            leftPiece -= pbills[i].outPiece;
                            leftLength -= pbills[i].outLength;
                        }
                    }
                    leftLength=Number(leftLength.toFixed(1))
                    if(leftPiece < outPiece || leftLength < outLength){
                        res.json({
                            code:200,
                            leftPiece: leftPiece,
                            leftLength: leftLength
                        });
                    }
                    else{
                        ProcessBill.updateOne({_id: id}, data)
                        .then(data=>{
                            console.log('update',data);
                            res.json({
                                code:200,
                                data:data
                            });
                        })
                        .catch(err=>{
                            res.json({
                                code:404,
                                data:err
                            })
                            console.log(err)
                        })
                    }
                })
            })
})

router.post("/processBill/delete",(req,res)=>{
    const id = req.query._id;
    ProcessBill.deleteOne({_id: id})
    .then(()=>{
        // console.log('delete',data);
        res.json({
            code:200,
            message:'删除成功'
        });
    })
})

// ================================================加工退回单==================================
router.post("/processReturnBill/add",(req,res)=>{
    ProcessBill.find({name:req.query.name, number:req.query.number, company:req.query.company})
    .then(pbills=>{
        let index = pbills.length;
        let pieceSum = 0;
        let lengthSum = 0;
        for(let i=0;i<index;i++){
            pieceSum+=pbills[i].outPiece;
            lengthSum+=pbills[i].outLength;
        }
        if(pieceSum == 0 || req.query.piece == 0){
            res.json({
                code:404,
                data:'发入发出不能为0'
            })
        }
        ProcessReturnBill.find({name:req.query.name, number:req.query.number, company:req.query.company})
        .then(rbills=>{
            let inPieceSum = 0;
            let index_ = rbills.length;
            for(let i=0;i<index_;i++){
                inPieceSum += rbills[i].piece;
            }
            let leftPiece = pieceSum - inPieceSum;
            
            if((inPieceSum + Number(req.query.piece)) > pieceSum){
                res.json({
                    code:200,
                    leftPiece: leftPiece,
                });
            }
            else{
                req.query.length = Number(req.query.length);
                req.query.piece = Number(req.query.piece);
                var rate = ((req.query.length / req.query.piece - lengthSum / pieceSum) / (req.query.length / req.query.piece));
                // console.log(req.query.length, req.query.piece, lengthSum, pieceSum, rate);
                let processReturnBill=new ProcessReturnBill({
                    name:req.query.name,
                    number:req.query.number,
                    piece:req.query.piece,
                    length:req.query.length,
                    warehouse:req.query.warehouse,
                    company:req.query.company,
                    rate:rate,
                    date:req.query.date,
                    operator:req.query.operator,
                    remark:req.query.remark,
                })
                processReturnBill.save()
                .then(bill=>res.json({
                    code:200,
                    data:bill
                }))
                .catch(err=>{
                    res.json({
                        code:404,
                        data:err
                    })
                    console.log(err)
                })
            }
        })
        
    })
    
})

router.post("/processReturnBill/getList",(req,res)=>{
    const limit=Number(req.query.limit);
    const page=Number(req.query.page);
    const match = {};
    const datelimit = {};
    let dateflag = false;
    for(let i in req.query){
        if(i!='limit' && i!=='page' && i!='datestart' && i!='dateend' && i!="sort"){
            match[i] = req.query[i];
        }
        else if(i =='datestart'){
            datelimit.$gte = req.query[i];
            dateflag = true;
        }
        else if(i == 'dateend'){
            datelimit.$lte = req.query[i];
            dateflag = true;
        }
    }
    const sortLimit = {date:req.query.sort?Number(req.query.sort):-1}
    if(dateflag) match['date'] = datelimit;
    ProcessReturnBill.find(match)
    .sort(sortLimit)
    .then(bills=>{
        const pageList = bills.filter((item, index) => index < limit * page && index >= limit * (page - 1))
        res.json({
            code:200,
            list:pageList,
            total:bills.length
        });
    })
})

router.post("/processReturnBill/fetchSelectItem",(req,res)=>{
    const data = {
        code:200,
        warehouse:[],
        goods:[],
        goodsNumber:{},
    }
    BilletedWarehouse.find({})
    .then(billetedWarehouse=>{
        
        let billetedWarehouseName = billetedWarehouse.map(v=>v.name);
        data.warehouse = data.warehouse.concat(billetedWarehouseName);
        Variety.find({})
        .then(goods=>{
            for(let i=0;i<goods.length;i++){
                data.goods.push(goods[i].name);
                data.goodsNumber[goods[i].name] = goods[i].number.map(v=>v.code);
            }
            ProcessingCompany.find({})
            .then(companies=>{
                data.companies = companies.map(v=>v.name);
                res.json(data);
            })
            .catch(err=>{
                res.json(data)
                console.log(err)
            })
        })
        .catch(err=>{
            res.json(data)
            console.log(err)
        })
    })
    .catch(err=>{
        res.json(data)
        console.log(err)
    })
    
})

router.post("/processReturnBill/update",(req,res)=>{
    const id = req.body._id;
    
    ProcessBill.find({name:req.body.name, number:req.body.number, company:req.body.company})
    .then(pbills=>{
        let index = pbills.length;
        let pieceSum = 0;
        let lengthSum = 0;
        for(let i=0;i<index;i++){
            pieceSum+=pbills[i].outPiece;
            lengthSum+=pbills[i].outLength;
        }
        if(pieceSum == 0 || req.body.piece == 0){
            res.json({
                code:404,
                data:'发入发出不能为0'
            })
        }
        ProcessReturnBill.find({name:req.body.name, number:req.body.number, company:req.body.company})
        .then(rbills=>{
            let inPieceSum = 0;
            let index_ = rbills.length;
            for(let i=0;i<index_;i++){
                inPieceSum += rbills[i].piece;
            }
            req.body.length = Number(req.body.length);
            req.body.piece = Number(req.body.piece);
            req.body.oldPiece = Number(req.body.oldPiece);
            let leftPiece = pieceSum - inPieceSum + req.body.oldPiece;
            if((inPieceSum - req.body.oldPiece + req.body.piece) > pieceSum){
                res.json({
                    code:200,
                    leftPiece: leftPiece,
                });
            }
            else{
                
        
                var rate = ((req.body.length / req.body.piece - lengthSum / pieceSum) / (req.body.length / req.body.piece));
                
                const data = {
                    name:req.body.name,
                    number:req.body.number,
                    piece:req.body.piece,
                    length:req.body.length,
                    warehouse:req.body.warehouse,
                    company:req.body.company,
                    rate:rate,
                    date:req.body.date,
                    operator:req.body.operator,
                    remark:req.body.remark,
                }
                ProcessReturnBill.updateOne({_id: id}, data)
                .then(()=>{
                    // console.log('update',data);
                    res.json({
                        code:200,
                        data:data,
                    });
                })
            }
        })
        
    })
    
    
})

router.post("/processReturnBill/delete",(req,res)=>{
    const id = req.query._id;
    ProcessReturnBill.deleteOne({_id: id})
    .then(()=>{
        // console.log('delete',data);
        res.json({
            code:200,
            message:'删除成功'
        });
    })
})


//===================================================加工统计=======================================

router.post("/processStatistics/fetchSelectItem",(req,res)=>{
    const data = {
        code:200,
        goods:[],
        goodsNumber:{},
        companies:[],
    }
    
    Variety.find({})
    .then(goods=>{
        for(let i=0;i<goods.length;i++){
            data.goods.push(goods[i].name);
            data.goodsNumber[goods[i].name] = goods[i].number
        }
        ProcessingCompany.find({})
        .then(companies=>{
            data.companies = companies.map(v=>v.name);
            res.json(data);
        })
        .catch(err=>{
            res.json(data)
            console.log(err)
        })
    })
    .catch(err=>{
        res.json(data)
        console.log(err)
    })
   
    
})

router.post("/processStatistics/getList",(req,res)=>{
    let query = JSON.parse(req.query.query);
    const limit=Number(query.limit);
    const page=Number(query.page);
    const match = {};
    const datelimit = {};
    let dateflag = false;
    for(let i in query){
        if(i!='limit' && i!=='page' && i!='datestart' && i!='dateend' && i!="sort"){
            match[i] = query[i];
        }
        else if(i =='datestart'){
            datelimit.$gte = new Date(query[i]);
            dateflag = true;
        }
        else if(i == 'dateend'){
            datelimit.$lte = new Date(query[i]);
            dateflag = true;
        }
    }
    const sortLimit = {date:query.sort?Number(query.sort):-1}
    if(dateflag) match['date'] = datelimit;
    let groupWord = {};
    req.query.method = JSON.parse(req.query.method);
    for(let i in req.query.method.checkList){
        if(req.query.method.checkList[i] == "按照加工企业统计"){
            groupWord.company = "$company";
        }
        else if (req.query.method.checkList[i] == "按照产品名称统计"){
            groupWord.name = "$name";
        }
        else if (req.query.method.checkList[i] == "按照产品号码统计"){
            groupWord.number = "$number";
        }
    }
    // console.log(match);
    ProcessBill.aggregate([{$match:match},
        {
            $group:{_id:groupWord, 
            outPiece:{$sum:'$outPiece'},
            outLength:{$sum:'$outLength'},
            }
        },
        
    {$sort:sortLimit},
    {$skip: limit * (page - 1)},
    {$limit: limit}])
    .exec((error, bills)=>{
        // console.log('bill',bills);
        const pageList = bills.filter((item, index) => index < limit * page && index >= limit * (page - 1));
        ProcessReturnBill.aggregate([{$match:match},
            {
                $group:{_id:groupWord, 
                piece:{$sum:'$piece'},
                length:{$sum:'$length'},
                money:{$sum:'$finishMoney'},
                },
            }])
            .exec((error, pbills)=>{
                // console.log('pbill',pbills);
                let obj_1 = {};
                let obj_2 = {};
                for(let i in pageList){
                    let key = JSON.stringify(pageList[i]._id);
                    obj_1[key] = pageList[i];
                }
                for(let i in pbills){
                    let key = JSON.stringify(pbills[i]._id);
                    obj_2[key] = pbills[i];
                }

                for(let i in obj_1){
                    if(obj_2[i] != undefined){
                        obj_1[i].inPiece = obj_2[i].piece;
                        obj_1[i].inLength = obj_2[i].length;
                        obj_1[i].leftPiece = obj_1[i].outPiece - obj_1[i].inPiece;
                        obj_1[i].rate = ((obj_1[i].inLength / obj_1[i].inPiece - obj_1[i].outLength / obj_1[i].outPiece) / (obj_1[i].inLength / obj_1[i].inPiece));
                    }
                }

                let pageList_ = [];
                for(let i in obj_1){
                    pageList_.push(obj_1[i]);
                }
                res.json({
                    code:200,
                    list:pageList_,
                    total:bills.length
                });
            })
    })
})

module.exports=router;